package spittr.config;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder;
import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType;
import org.springframework.orm.hibernate5.LocalSessionFactoryBean;
import org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor;

import javax.sql.DataSource;
import java.util.Properties;

@Configuration

public class DataConfig {


    @Profile("development")
    @Bean
    public DataSource dataSourceH2(){

        System.out.println("init datasource");
        return  new EmbeddedDatabaseBuilder()
                .setType(EmbeddedDatabaseType.H2)
                .addScript("schema.sql")
                .build();
    }


    @Profile("production")
    @Bean
    public DataSource dataSourcePro(){
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName("org.postgresql.Driver");
        dataSource.setUsername("lxys");
        dataSource.setPassword("lxys");
        dataSource.setUrl("jdbc:postgresql://47.93.248.193:5432/lxys");
        dataSource.setInitialSize(1);
        dataSource.setMaxTotal(50);
        dataSource.setPoolPreparedStatements(true);//是否对预处理语句经行池管理

        return  dataSource;
    }


    @Bean
    public JdbcTemplate jdbcTemplate(DataSource dataSource){
        return new JdbcTemplate(dataSource);
    }


    @Bean
    public LocalSessionFactoryBean sessionFactory(DataSource dataSource){
        LocalSessionFactoryBean sessionFactoryBean = new LocalSessionFactoryBean();
        sessionFactoryBean.setDataSource(dataSource);

        sessionFactoryBean.setPackagesToScan("spittr");

        Properties properties = new Properties();
        //properties.put(org.hibernate.cfg.Environment.USER,"lxys");
        //properties.put(org.hibernate.cfg.Environment.PASS,"lxys");
        //properties.put(org.hibernate.cfg.Environment.URL,"jdbc:postgresql://47.93.248.193:5432/lxys");
        //properties.put(org.hibernate.cfg.Environment.DRIVER,"org.postgresql.Driver");
        properties.put(org.hibernate.cfg.Environment.DIALECT,"org.hibernate.dialect.PostgreSQLDialect");

        properties.put(org.hibernate.cfg.Environment.SHOW_SQL,"true");
        sessionFactoryBean.setHibernateProperties(properties);
        return  sessionFactoryBean;

    }


    /**
     * 异常转换器
     * @return
     */
    @Bean
    public BeanPostProcessor persistenceTranslation(){
        return new PersistenceAnnotationBeanPostProcessor();
    }

}
